package cn.wsalix.weixin.service.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.Observable;

import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.anlaser.service.impl.SimpleServiceImpl;
import cn.anlaser.utils.FastJsonMapper;
import cn.anlaser.utils.HttpUtils;
import cn.anlaser.utils.SearchFilter;
import cn.anlaser.utils.SearchFilter.Operator;
import cn.wsalix.admin.entity.SysUser;
import cn.wsalix.constant.WxGlobal;
import cn.wsalix.observable.service.LoginService;
import cn.wsalix.shiro.token.WxAppToken;
import cn.wsalix.utils.UserUtils;
import cn.wsalix.weixin.entity.WxUser;
import cn.wsalix.weixin.form.WxUserForm;
import cn.wsalix.weixin.repository.WxUserRepository;
import cn.wsalix.weixin.service.WxUserService;

@Service("wxUserService")
public class WxUserServiceImpl extends
		SimpleServiceImpl<WxUserForm, WxUserRepository, WxUser> implements
		WxUserService {
	@Autowired
	private WxUserRepository wxUserRepository;
	@Autowired
	protected UserUtils userUtils;

	@Override
	public String module() {
		return "/wx/user";
	}

	@Override
	public WxUserRepository getRepository() {
		return wxUserRepository;
	}

	@Override
	public Class<WxUser> getEntityClazz() {
		return WxUser.class;
	}

	@Override
	public Map<String, SearchFilter> buildByForm(WxUserForm form) {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);

		if (form.getName() != null && !form.getName().equals("")) {
			filters.put("name",
					new SearchFilter("nama", Operator.EQ, form.getName()));
		}

		return filters;
	}

	@Transactional
	@Override
	public void update(Observable o, Object arg) {
		if (o instanceof LoginService) {
			LoginService loginService = (LoginService) o;
			if (arg instanceof WxAppToken) {
				SysUser user=loginService.getUser();
				WxAppToken upToken = (WxAppToken) arg;
				WxUser wxUser = add(upToken,user);
				upToken.setWxUser(wxUser);
			}
		}
	}

	private WxUser add(WxAppToken upToken,SysUser user) {
		if (upToken.getAccess_token() == null) {//未传入Access_token，信息不可信
			WxUser wxUser = wxUserRepository.findByOpenIdOne(upToken
					.getOpenid());
			if (wxUser == null) {
				wxUser = new WxUser();
				wxUser.setOpenid(upToken.getOpenid());
				wxUser.setNickname(upToken.getUsername());
				wxUser = wxUserRepository.save(wxUser);
			}
			return wxUser;
		} else {//传入Access_token，从微信服务器获取信息
			String url = WxGlobal.doGetAppUserInfo(upToken.getAccess_token(),
					upToken.getOpenid());
			String userInfoStr = HttpUtils.getToString(url);
			WxUser wxUser = FastJsonMapper.fromJson(userInfoStr, WxUser.class);
			if (wxUser == null || !wxUser.getErrcode().equals("0")) {
				throw new AuthenticationException("获取用户信息错误["
						+ wxUser.getErrcode() + "]，微信登录失败");
				// wxUser.getErrcode() + "," + wxUser.getErrmsg());
			}
			WxUser wxUserDb = wxUserRepository.findByOpenIdOne(upToken
					.getOpenid());
			if (wxUserDb == null) {
				if (user != null) {// 用户已登录，自动绑定账号					
					wxUser.setUser(user);
				}
				wxUserDb = wxUserRepository.save(wxUser);
			}
			return wxUserDb;
		}

	}

}
